package com.bite.blog.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.DigestUtils;

import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.UUID;

@Slf4j
public class SecurityUtils {
    /**
     * 加密
     */
    public static String encrypt(String password) {
        log.info("加密数据");
        String salt = UUID.randomUUID().toString().replace("-", "");
        String md5 = null;
        try {
            md5 = DigestUtils.md5DigestAsHex((salt + password).getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            log.error("getBytes 错误 e:", e);
            throw new RuntimeException(e);
        }
        return md5 + salt;
    }

    /**
     * 解密
     */
    public static Boolean verity(String password, String finalPassword) {
        log.info("校验密码");
        if (password == null || finalPassword == null || finalPassword.length() != 64) {
            log.error("密码格式不对");
            return false;
        }
        String salt = finalPassword.substring(32, 64);
        String md5 = null;
        try {
            md5 = DigestUtils.md5DigestAsHex((salt + password).getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            log.error("getBytes 错误 e:", e);
            throw new RuntimeException(e);
        }
        return finalPassword.equals(md5 + salt);
    }

}
